import { _decorator, Component, Node, Prefab, instantiate, Vec3, resources, Collider2D, Contact2DType, director, UITransform, Label, IPhysics2DContact, AudioSource, Animation, tween, math, Button, Tween, RichText } from 'cc';
import { BirdController } from './BirdController';
import { ArrowController } from './ArrowController';
import { BackgroundScroller } from './BackgroundScroll';
const { ccclass, property } = _decorator;

@ccclass('GameManager')
export class GameManager extends Component {

    // 5秒出现第二个射手
    private showShooter:number = 15;

    @property([Node])
    shooters: Node[] = [];  // 所有预置好的射手节点（Shooter A、B、C...）
    // private shooterScheduleIds: number[] = []; // 每个射手的 schedule ID
    private shooterCallbacks: ((...args: any[]) => void)[] = [];



    @property(Prefab)
    arrowPrefab: Prefab = null;

    @property(Node)
    arrowContainer: Node = null;

    @property(Node)
    bird: Node = null;

    @property(Node)
    gameOverUI: Node = null;

    private elapsedTime = 0;
    private activeShooters: number = 0; // 当前启用的射手数量


    // private spawnInterval = 0.5;
    // private timer = 0;
    private isGameOver = true;



    @property(Prefab)
    foodPrefab: Prefab = null;
    @property(Node)
    foodParent: Node = null;
    @property(Label)
    scoreLabel: Label = null;

    @property(RichText)
    finalScoreLab: RichText = null;

    private _score = 0;

    @property({ type: AudioSource })
    bgmAudioSource: AudioSource = null!;

    // 射手A在圆形范围内随机移动
    centerOfShooterA: Vec3 = new Vec3(290, 540, 0); // 圆心
    // 射手B在圆形范围内随机移动
    centerOfShooterB: Vec3 = new Vec3(290, 285, 0); // 圆心
    centerOfShooterC: Vec3 = new Vec3(290, 47, 0); // 圆心
    centerOfShooterD: Vec3 = new Vec3(290, -175, 0); // 圆心

    @property
    radius: number = 60; // 移动范围半径

   
    moveDuration: number = 3; // 每次移动耗时


    @property(Node)
    startUINode:Node = null;

    @property(Button)
    startButton: Button = null;

    @property(Node)
    BackgroundGroup:Node = null;

    start() {
        this.playBGM();
    }

   startShooterFiring(index: number, interval: number) {
        const callback = this.fireFromShooter.bind(this, index);
        this.shooterCallbacks[index] = callback;
        this.schedule(callback, interval);
    }

    stopAllShooterFiring() {
        this.shooterCallbacks.forEach((callback) => {
            if (callback) {
                this.unschedule(callback);
            }
        });
        this.shooterCallbacks = [];
    }




     playBGM() {
        if (this.bgmAudioSource) {
            //:在 Web 平台，Auto Play Policy 禁止首次自动播放音频，因为需要发生用户交互之后才能播放音频。 有两种方式实现音频首次自动播放：
            // 在 TOUCH_END 或者 MOUSE_UP 的事件回调里播放音频。
            // 直接播放音频，引擎会在下一次发生用户交互时自动播放
            const id = this.bgmAudioSource.play();
            // console.log("播放的音频 ID:", id);
        }
    }


    updateTimer() {
        this.elapsedTime++;

        if (this.elapsedTime % this.showShooter == 0) {
            const nextShooterIndex = this.activeShooters;
            
            if (nextShooterIndex < this.shooters.length) {
                const newShooter = this.shooters[nextShooterIndex];
                newShooter.active = true;
                 this.randomMove(nextShooterIndex);
                if(nextShooterIndex ==1){
                    // this.schedule(this.fireFromShooter.bind(this, nextShooterIndex), 2);
                     this.startShooterFiring(nextShooterIndex, 2.5);
                }else if(nextShooterIndex ==2){
                    // this.schedule(this.fireFromShooter.bind(this, nextShooterIndex), 2.5);
                     this.startShooterFiring(nextShooterIndex, 3);
                }else if(nextShooterIndex == 3){
                    // this.schedule(this.fireFromShooter.bind(this, nextShooterIndex), 3);
                     this.startShooterFiring(nextShooterIndex, 2);
                }
                
                this.activeShooters++;
            }
        }
    }

    fireFromShooter(index: number) {
        // console.log('射箭')
        if (this.isGameOver) return;

        const shooter = this.shooters[index];
        if (!shooter || !this.arrowPrefab || !this.bird) return;

        const arrow = instantiate(this.arrowPrefab);

        // 添加到容器后再设置位置！(***必须先指定父亲，再设置位置不然弓箭不是从射手位置出来)
        this.arrowContainer.addChild(arrow);

        const shooterPos = shooter.getWorldPosition();
        arrow.setWorldPosition(shooterPos);

        //预制体后面想要调用GameManager中的方法，必须有下面两行代码，不然预制体调用方法时报NULL
        const arrowCtrl = arrow.getComponent(ArrowController);
         arrowCtrl.gameManager = this; //this 就是 GameManager 实例
        // console.log('生成弓箭'+ arrow.position)
        // console.log('射手位置', shooterPos);
        // console.log('弓箭位置', arrow.getWorldPosition());

        // 计算方向
        const birdPos = this.bird.getWorldPosition();
        const addYPos = new Vec3(birdPos.x,birdPos.y+100,birdPos.z);
        const direction = new Vec3();
        Vec3.subtract(direction, addYPos, shooterPos);
        direction.normalize();

        const angleRad = Math.atan2(direction.y, direction.x);
        // arrow.setRotationFromEuler(0, 0, angleRad * 180 / Math.PI);
        // arrow.setRotationFromEuler(0, 0, angleRad * (-180));

        const arrowScript = arrow.getComponent(ArrowController);
        if (arrowScript) {
            arrowScript.setDirection(direction);
        }

        // 设置事件监听
        // arrow.on('GameOver', this.onGameOver, this);
    }

  
    /**
     物理碰撞回调中的逻辑不要直接添加带刚体的新节点，否则你可能会在物理引擎尚未准备好时操作了未初始化的刚体，造成运行时崩溃。
     在回调中不要直接操作刚体节点
     而是 等到下一帧 再安全地添加，比如：
         使用 scheduleOnce(() => ..., 0);
         在 update() 中统一处理标志位（推荐）
         使用 Director.instance.once(Director.EVENT_AFTER_UPDATE, ...)


     spawnFood() {
        
        const newFood = instantiate(this.foodPrefab);
        console.log(newFood.name);
        console.log(this.foodParent.name);
        console.log('到这里');
        this.foodParent.addChild(newFood);
        console.log('成功')
    }
     */


    public addScore(num:number) {
       
       // 打中敌人加1分，吃到食物加5分
        this._score = this._score +num;
        this.scoreLabel.string = `${this._score}`;
    }

    public spawnFood() {
         this.scheduleOnce(() => {
                if (!this.foodPrefab || !this.foodParent) return;
                const newFood = instantiate(this.foodPrefab);
                this.foodParent.addChild(newFood);

                //x轴方向-350到50之间
                const x = Math.random() * (50 - (-350)) + (-350);  
                //y轴方向在-100到600之间
                const y = Math.random() * (600 - (-100)) + (-100);  
                         
                // 设置的位置是相对于父节点的
                newFood.setPosition(x, y);
            

                // console.log('到这里呀' + newFood.position)
               
            }, 0);


       
    }
    

    onGameOver() {
        // console.log('游戏结束，弹出界面');
        this.isGameOver = true;
        // 显示重新开始的 UI 节点
        this.gameOverUI.active = true;
        this.finalScoreLab.string= `得分：${this._score}`;
        
    }

    onRestartGame() {
       
        this.stopAllShooterFiring();

        // 背景图回到最初位置
        const bg = this.BackgroundGroup.getComponent(BackgroundScroller)
        bg.onRestartGame();
        
        
         // 停止所有射手船 tween,射手船回到初始位置
        this.shooters.forEach(shooter => {
            Tween.stopAllByTarget(shooter); // 停止它的移动动画
        });
        this.shooters[0].setPosition(380,503.701);
        this.shooters[1].setPosition(380,285);
        this.shooters[2].setPosition(380,47);
        this.shooters[3].setPosition(380,-175);
        this.onClickStartButton();
        
       
        // 小鸟回到初始位置
        const birdCtrl = this.bird.getComponent(BirdController);
        birdCtrl.isAlive = true;
        this.bird.setPosition(-274,0);
        // 分数归零
        this._score = 0;
        this.scoreLabel.string = `${this._score}`;
          // 延迟2秒再射箭
        this.scheduleOnce(() => {
           this.isGameOver = false; 
        }, 2);
    }

    revive() {
        const birdCtrl = this.bird.getComponent(BirdController);
        birdCtrl.isAlive = true;

        // 可选：重置小鸟位置/播放复活动画
        this.bird.setPosition(0, 0); // 回到起始位置
         // 获取碰撞控制组件并触发无敌
        const control = this.bird.getComponent(BirdController);
        if (control) {
            control.startInvincible();
            // console.log("[复活系统] 触发2秒内无敌状态");
        }

        // 延迟2秒再射箭
        this.scheduleOnce(() => {
           this.isGameOver = false; 
        }, 2);

    }

    onClickStartButton(){
        this.elapsedTime = 0;
        this.activeShooters = 1;
        this.isGameOver = false;
        // this.gameOverUI.active = false;

        this.randomMove(0);

        // 激活第一个射手
        if (this.shooters.length > 0) {
            // this.shooters[0].active = true;
            // this.schedule(this.fireFromShooter.bind(this, 0), 1.5);
            this.startShooterFiring(0, 1.5);

        }

        // 关键：每秒执行一次 updateTimer,过十秒后出现下一个射手
        this.schedule(this.updateTimer, 1);

        // 原有每0.5秒随机箭（可选）
        // this.schedule(this.spawnArrow.bind(this), this.spawnInterval);
        // this.spawnFood();

    }
   
    // 船在指定范围内移动
    randomMove(shooterNum: number) {
        // 随机角度
        const angle = math.randomRange(0, 2 * Math.PI);
        const offsetX = Math.cos(angle) * this.radius;
        const offsetY = Math.sin(angle) * this.radius;
        let targetPos = null;
        if(shooterNum ==0){
                targetPos = new Vec3(
                this.centerOfShooterA.x + offsetX,
                this.centerOfShooterA.y + offsetY,
                0
            );
        }else if(shooterNum ==1){
                targetPos = new Vec3(
                this.centerOfShooterB.x + offsetX,
                this.centerOfShooterB.y + offsetY,
                0
            );

        }else if(shooterNum ==2){
                targetPos = new Vec3(
                this.centerOfShooterC.x + offsetX,
                this.centerOfShooterC.y + offsetY,
                0
            );

        }else if(shooterNum ==3){
                targetPos = new Vec3(
                this.centerOfShooterD.x + offsetX,
                this.centerOfShooterD.y + offsetY,
                0
            );

        }
       

        // tween 移动
        tween(this.shooters[shooterNum])
            .to(this.moveDuration, { position: targetPos }, { easing: 'sineInOut' })
            .call(() => {
                // 完成后继续随机下一个点
                this.randomMove(shooterNum);
            })
            .start();
    }

}







